package com.d3works.apps.sale.db.repo;

import com.d3works.apps.sale.db.ConfiguratorCreator;
import com.d3works.apps.sale.exception.SaleExceptionMessage;
import com.d3works.apps.sale.service.configurator.ConfiguratorCreatorImportService;
import com.d3works.apps.sale.service.configurator.ConfiguratorCreatorService;
import com.d3works.exception.service.TraceBackService;
import com.d3works.i18n.I18n;
import com.d3works.inject.Beans;
import com.d3works.meta.db.MetaJsonField;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import javax.persistence.PersistenceException;

public class ConfiguratorCreatorSaleRepository extends ConfiguratorCreatorRepository {

  @Override
  public ConfiguratorCreator copy(ConfiguratorCreator entity, boolean deep) {
    ConfiguratorCreator copy = super.copy(entity, deep);
    copy.setCopyNeedingUpdate(true);
    copy.setName(copy.getName() + " (" + I18n.get(SaleExceptionMessage.COPY) + ")");
    addTemporalOnAttributesAndIndicatorsName(copy);
    return copy;
  }

  @Override
  public ConfiguratorCreator save(ConfiguratorCreator entity) {
    try {
      if (entity.getCopyNeedingUpdate()) {
        entity = super.save(entity);
        entity.setCopyNeedingUpdate(false);
        ConfiguratorCreatorService configuratorCreatorService =
            Beans.get(ConfiguratorCreatorService.class);
        Beans.get(ConfiguratorCreatorImportService.class).fixAttributesName(entity);
        configuratorCreatorService.updateAttributes(entity);
        configuratorCreatorService.removeTemporalAttributesAndIndicators(entity);
        configuratorCreatorService.updateIndicators(entity);
        return entity;
      } else {
        return super.save(entity);
      }
    } catch (Exception e) {
      TraceBackService.traceExceptionFromSaveMethod(e);
      throw new PersistenceException(e.getMessage(), e);
    }
  }

  /**
   * Quick fix for constrainst issue
   *
   * @param entity
   */
  protected void addTemporalOnAttributesAndIndicatorsName(ConfiguratorCreator entity) {
    List<MetaJsonField> metaJsonFields = new ArrayList<>();
    metaJsonFields.addAll(
        Optional.ofNullable(entity.getAttributes()).orElse(Collections.emptyList()));
    metaJsonFields.addAll(
        Optional.ofNullable(entity.getIndicators()).orElse(Collections.emptyList()));
    for (MetaJsonField metaJsonField : metaJsonFields) {
      String name = metaJsonField.getName();
      if (name != null) {
        // FIX FOR CONSTRAINT ISSUE
        metaJsonField.setName(name + "$D3WORKSTMP");
      }
    }
  }
}
